<template>
  <div class="points-mall">
    <div class="header">
      <div class="nav-bar">
        <div class="nav-title">积分商城</div>
        <div class="nav-actions">
          <div class="nav-action" @click="goToPointsEarnHistory">
            积分记录
          </div>
          <div class="nav-action" @click="goToPurchaseHistory">
            购买记录
          </div>
        </div>
      </div>
      <div class="points-info">
        <div class="points-title">我的积分</div>
        <div class="points-value">{{ userPoints }}</div>
      </div>
    </div>

    <div class="mall-content">
      <div class="section-title">商品分类</div>

      <div class="category-list">
        <div
          class="category-item"
          v-for="category in categories"
          :key="category.id"
          @click="viewCategoryProducts(category)"
        >
          <div class="category-image">
            <img :src="category.image" alt="分类图片" />
          </div>
          <div class="category-info">
            <div class="category-name">{{ category.name }}</div>
            <div class="category-desc">{{ category.description }}</div>
          </div>
          <div class="category-arrow">></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from '@/api'

export default {
  name: 'PointsMall',
  data() {
    return {
      userPoints: 0,
      currentStudent: null,
      categories: [
        {
          id: 1,
          name: '专属文具套装',
          description: '精选优质文具，提升学习效率',
          image: require('@/assets/wenju.png')
        },
        {
          id: 2,
          name: '专属玩具套装',
          description: '益智玩具，寓教于乐',
          image: require('@/assets/wanju.png')
        },
        {
          id: 3,
          name: '课程优惠券',
          description: '多种课程优惠，节省学习成本',
          image: require('@/assets/zhekou.png')
        },
        {
          id: 4,
          name: 'VIP课程体验',
          description: '高端课程体验，享受专属服务',
          image: require('@/assets/VIP-kecheng.png')
        }
      ]
    }
  },
  created() {
    // 获取路由参数中的学生信息
    this.currentStudent = this.$route.params.studentInfo || null

    // 检查是否是从分类商品页面返回
    this.checkIfFromCategoryProducts()

    // 进入页面时根据学生ID调用接口获取详细信息并更新缓存
    this.fetchStudentDetail()
  },
  methods: {
    // 根据学生ID获取学生详细信息并更新缓存
    async fetchStudentDetail() {
      // 获取学生ID，优先从路由参数中获取，如果没有则从当前学生对象中获取
      let studentId = null
      let source = ''

    // 检查是否是从分类商品页面、购买记录页面或积分记录页面返回
    const fromCategoryProducts = this.$route.params.fromCategoryProducts
    const fromPurchaseHistory = this.$route.params.fromPurchaseHistory
    const fromPointsEarnHistory = this.$route.params.fromPointsEarnHistory
    const cachedStudentInfo = localStorage.getItem('currentStudentInfo')

    if ((fromCategoryProducts || fromPurchaseHistory || fromPointsEarnHistory) && cachedStudentInfo) {
      // 从相关页面返回，使用缓存中的学生ID
      try {
        const cachedStudent = JSON.parse(cachedStudentInfo)
        if (cachedStudent && cachedStudent.id) {
          studentId = cachedStudent.id
          source = 'cache'

          if (fromCategoryProducts) {
            console.log('从分类商品页面返回，使用缓存中的学生ID:', studentId)
          } else if (fromPurchaseHistory) {
            console.log('从购买记录页面返回，使用缓存中的学生ID:', studentId)
          } else if (fromPointsEarnHistory) {
            console.log('从积分记录页面返回，使用缓存中的学生ID:', studentId)
          }
        }
      } catch (error) {
        console.error('解析缓存学生信息失败:', error)
      }
    } else if (this.$route.params.studentInfo && this.$route.params.studentInfo.id) {
        // 从路由参数中获取学生ID
        studentId = this.$route.params.studentInfo.id
        source = 'route'
        console.log('从路由参数获取学生ID:', studentId)
      } else if (this.currentStudent && this.currentStudent.id) {
        // 从当前学生对象中获取学生ID
        studentId = this.currentStudent.id
        source = 'current'
        console.log('从当前学生对象获取学生ID:', studentId)
      }

      if (!studentId) {
        console.warn('没有有效的学生ID，跳过获取学生详细信息')
        return
      }

      try {
        console.log('开始获取学生详细信息，学生ID:', studentId, '来源:', source)
        const response = await api.getStudentById({ studentId: studentId })

        if (response.data.code === 200 && response.data.result) {
          const studentDetail = response.data.result
          console.log('获取到学生详细信息:', studentDetail)

          // 更新当前学生信息
          this.currentStudent = {
            ...this.currentStudent,
            ...studentDetail
          }

          // 更新缓存
          localStorage.setItem('currentStudentInfo', JSON.stringify(this.currentStudent))
          console.log('学生信息已更新到缓存')

          // 更新积分显示
          this.getUserPoints()
        } else {
          console.error('获取学生详细信息失败:', response.data.message)
        }
      } catch (error) {
        console.error('调用获取学生详细信息接口失败:', error)
      }
    },

    getUserPoints() {
      // 根据学生信息获取积分，使用 studentPoints 字段
      if (this.currentStudent) {
        // 如果有具体学生信息，使用学生对象中的 studentPoints 字段
        this.userPoints = this.currentStudent.studentPoints || 0
      } else {
        // 如果没有学生信息，使用默认积分
        this.userPoints = 0
      }
    },
    viewCategoryProducts(category) {
      // 添加跳转日志
      console.log('跳转到分类商品页面:', {
        categoryId: category.id,
        categoryName: category.name,
        studentInfo: this.currentStudent,
        timestamp: new Date().toISOString()
      })

      this.$router.push({
        name: 'categoryProducts',
        params: {
          categoryId: category.id,
          categoryName: category.name,
          studentInfo: this.currentStudent
        }
      })
    },
    goToPointsEarnHistory() {
      this.$router.push({
        name: 'pointsEarnHistory',
        params: { studentInfo: this.currentStudent }
      })
    },
    goToPurchaseHistory() {
      this.$router.push({
        name: 'purchaseHistory',
        params: { studentInfo: this.currentStudent }
      })
    },

    // 检查是否是从相关页面返回
    checkIfFromCategoryProducts() {
      // 使用 sessionStorage 来标记页面来源
      const fromCategoryProducts = sessionStorage.getItem('fromCategoryProducts')
      const fromPurchaseHistory = sessionStorage.getItem('fromPurchaseHistory')
      const fromPointsEarnHistory = sessionStorage.getItem('fromPointsEarnHistory')

      if (fromCategoryProducts === 'true') {
        // 设置路由参数，表示是从分类商品页面返回
        this.$route.params.fromCategoryProducts = true
        console.log('检测到从分类商品页面返回')

        // 清除标记
        sessionStorage.removeItem('fromCategoryProducts')
      }

      if (fromPurchaseHistory === 'true') {
        // 设置路由参数，表示是从购买记录页面返回
        this.$route.params.fromPurchaseHistory = true
        console.log('检测到从购买记录页面返回')

        // 清除标记
        sessionStorage.removeItem('fromPurchaseHistory')
      }

      if (fromPointsEarnHistory === 'true') {
        // 设置路由参数，表示是从积分记录页面返回
        this.$route.params.fromPointsEarnHistory = true
        console.log('检测到从积分记录页面返回')

        // 清除标记
        sessionStorage.removeItem('fromPointsEarnHistory')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.points-mall {
  width: 100%;
  height: 100%;
  background: #f6f8fc;

  .header {
    height: 120px;
    background: linear-gradient(135deg, #FF6B6B, #FF8E53);
    padding: 20px;
    color: white;

      .nav-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        .nav-title {
          font-size: 18px;
          font-weight: bold;
        }

        .nav-actions {
          display: flex;
          gap: 10px;

          .nav-action {
            font-size: 14px;
            padding: 4px 12px;
            border: 1px solid rgba(255, 255, 255, 0.5);
            border-radius: 15px;
            cursor: pointer;
            transition: all 0.3s;

            &:hover {
              background: rgba(255, 255, 255, 0.1);
            }
          }
        }
      }

    .points-info {
      text-align: center;

      .points-title {
        font-size: 16px;
        opacity: 0.9;
        margin-bottom: 8px;
      }

      .points-value {
        font-size: 32px;
        font-weight: bold;
      }
    }
  }

  .mall-content {
    padding: 20px;

    .section-title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 15px;
      color: #333;
    }

    .category-list {
      .category-item {
        background: white;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .category-image {
          width: 60px;
          height: 60px;
          border-radius: 6px;
          overflow: hidden;
          margin-right: 15px;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .category-info {
          flex: 1;

          .category-name {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
          }

          .category-desc {
            font-size: 12px;
            color: #999;
          }
        }

        .category-arrow {
          font-size: 16px;
          color: #ccc;
          font-weight: bold;
        }
      }
    }
  }
}
</style>
